<template>
  <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" width="800px">
    <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="订单信息" prop="orderInfo">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ state.form.orderCode }}</el-descriptions-item>
              <el-descriptions-item label="商品名称">{{ state.form.goodsName }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ state.form.quantity }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{ state.form.currentStatus }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select v-model="state.form.warehouseId" placeholder="请选择仓库" clearable filterable @change="onWarehouseChange">
              <el-option 
                v-for="warehouse in state.warehouseList" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="库位" prop="locationId">
            <el-select v-model="state.form.locationId" placeholder="请选择库位" clearable filterable :disabled="!state.form.warehouseId">
              <el-option 
                v-for="location in state.locationList" 
                :key="location.id" 
                :label="location.name" 
                :value="location.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘点数量" prop="stocktakingQuantity">
            <el-input-number 
              v-model="state.form.stocktakingQuantity" 
              :min="0" 
              placeholder="请输入盘点数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘点类型" prop="stocktakingType">
            <el-select v-model="state.form.stocktakingType" placeholder="请选择盘点类型" clearable>
              <el-option label="存货盘点" value="inventory" />
              <el-option label="期末盘点" value="periodEnd" />
              <el-option label="期初盘点" value="periodStart" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘点结果" prop="stocktakingResult">
            <el-select v-model="state.form.stocktakingResult" placeholder="请选择盘点结果" clearable>
              <el-option label="盘盈" value="surplus" />
              <el-option label="盘亏" value="loss" />
              <el-option label="账实相符" value="match" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘盈数量" prop="profitQuantity">
            <el-input-number 
              v-model="state.form.profitQuantity" 
              :min="0"
              :disabled="state.form.stocktakingResult !== 'surplus'"
              placeholder="请输入盘盈数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘盈金额" prop="profitAmount">
            <el-input-number 
              v-model="state.form.profitAmount" 
              :min="0"
              :precision="2"
              :disabled="state.form.stocktakingResult !== 'surplus'"
              placeholder="请输入盘盈金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘亏数量" prop="lossQuantity">
            <el-input-number 
              v-model="state.form.lossQuantity" 
              :min="0"
              :disabled="state.form.stocktakingResult !== 'loss'"
              placeholder="请输入盘亏数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="盘亏金额" prop="lossAmount">
            <el-input-number 
              v-model="state.form.lossAmount" 
              :min="0"
              :precision="2"
              :disabled="state.form.stocktakingResult !== 'loss'"
              placeholder="请输入盘亏金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="state.form.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="state.loading">确认盘点</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="stocktakingDialog">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useSysoutstockorderApi } from '/@/api/OutWarehou/sysoutstockorder';
import { useSysinstockorderApi } from '/@/api/OutWarehou/sysinstockorder';
import { useSysstocktakingorderApi } from '/@/api/OutWarehou/sysstocktakingorder';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { useWarePlaceModelApi } from '/@/api/interacting/warehouse/warePlaceModel';
import { useGoodsModelApi } from '/@/api/Goods/Details/goodsModel';

const emit = defineEmits(['confirm', 'cancel']);

const outstockApi = useSysoutstockorderApi();
const instockApi = useSysinstockorderApi();
const stocktakingApi = useSysstocktakingorderApi();
const warehouseApi = useWarehouseModelApi();
const warePlaceApi = useWarePlaceModelApi();
const goodsApi = useGoodsModelApi();
const formRef = ref();
const state = reactive({
  dialogVisible: false,
  dialogTitle: '盘点操作',
  loading: false,
  warehouseList: [] as any[],
  locationList: [] as any[],
  form: {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    currentStatus: '',
    warehouseId: null,
    locationId: null,
    stocktakingQuantity: 0,
    stocktakingType: 'inventory',
    stocktakingResult: '',
    profitQuantity: 0,
    profitAmount: 0,
    lossQuantity: 0,
    lossAmount: 0,
    remark: ''
  },
  rules: {
    warehouseId: [
      { required: true, message: '请选择仓库', trigger: 'change' }
    ],
    locationId: [
      { required: true, message: '请选择库位', trigger: 'change' }
    ],
    stocktakingQuantity: [
      { required: true, message: '请输入盘点数量', trigger: 'blur' },
      { type: 'number', min: 0, message: '盘点数量不能小于0', trigger: 'blur' }
    ],
    stocktakingType: [
      { required: true, message: '请选择盘点类型', trigger: 'change' }
    ]
  }
});

// 监听盘点结果变化，自动清空不相关字段
watch(() => state.form.stocktakingResult, (newValue) => {
  if (newValue === 'surplus') {
    // 选择盘盈时，清空盘亏数据
    state.form.lossQuantity = 0;
    state.form.lossAmount = 0;
  } else if (newValue === 'loss') {
    // 选择盘亏时，清空盘盈数据
    state.form.profitQuantity = 0;
    state.form.profitAmount = 0;
  } else if (newValue === 'match') {
    // 选择账实相符时，清空所有盘盈盘亏数据
    state.form.profitQuantity = 0;
    state.form.profitAmount = 0;
    state.form.lossQuantity = 0;
    state.form.lossAmount = 0;
  }
});

// 打开对话框
const openDialog = async (orderData: any) => {
  console.log('打开盘点对话框，订单数据:', orderData);
  console.log('仓库信息:', {
    warehouseName: orderData.warehouseName,
    warehouseNameDisplay: orderData.warehouseNameDisplay
  });
  console.log('商品名称字段:', {
    goodsName: orderData.goodsName,
    goodsNameDisplay: orderData.goodsNameDisplay,
    goodsCode: orderData.goodsCode
  });
  
  state.dialogVisible = true;
  state.form = {
    orderId: orderData.id,
    orderCode: orderData.code,
    goodsName: orderData.goodsNameDisplay || orderData.goodsName,
    quantity: orderData.quantity || orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    currentStatus: orderData.documentStatus,
    warehouseId: null,
    locationId: null,
    stocktakingQuantity: orderData.quantity || orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    stocktakingType: orderData.stockTakingType || 'inventory',
    stocktakingResult: orderData.inventoryResult || '',
    profitQuantity: orderData.profitQuantity || 0,
    profitAmount: orderData.profitAmount || 0,
    lossQuantity: orderData.lossQuantity || 0,
    lossAmount: orderData.lossAmount || 0,
    remark: orderData.remark || ''
  };
  
  console.log('表单初始化完成:', state.form);
  
  // 先加载仓库列表
  await loadWarehouseList();
  
  // 根据盘点单中的仓库名称或ID查找对应的仓库
  const warehouseKey = orderData.warehouseName || orderData.warehouseNameDisplay;
  console.log('盘点单中的仓库标识:', warehouseKey);
  
  if (warehouseKey) {
    await loadWarehouseByNameOrId(warehouseKey);
  } else {
    // 如果盘点单没有仓库信息，尝试通过商品查找
    const searchKey = orderData.goodsName || orderData.goodsCode || orderData.goodsNameDisplay;
    console.log('通过商品查询仓库，关键字:', searchKey);
    await loadWarehouseByGoodsName(searchKey);
  }
};

// 根据仓库名称或ID查找并选中仓库
const loadWarehouseByNameOrId = async (warehouseKey: string) => {
  if (!warehouseKey) {
    console.log('仓库标识为空');
    return;
  }
  
  console.log('开始查找仓库，标识:', warehouseKey, '类型:', typeof warehouseKey);
  console.log('当前仓库列表:', state.warehouseList);
  
  // 尝试多种匹配方式
  let matchedWarehouse = null;
  
  // 1. 尝试作为ID匹配（支持长数字字符串，如 "1500000000101"）
  const warehouseKeyStr = String(warehouseKey);
  matchedWarehouse = state.warehouseList.find(w => String(w.id) === warehouseKeyStr);
  if (matchedWarehouse) {
    console.log('通过ID字符串匹配到仓库:', matchedWarehouse);
  }
  
  // 2. 如果没匹配到，尝试作为数字ID匹配
  if (!matchedWarehouse) {
    const warehouseIdNum = parseInt(warehouseKey);
    if (!isNaN(warehouseIdNum)) {
      matchedWarehouse = state.warehouseList.find(w => w.id === warehouseIdNum);
      if (matchedWarehouse) {
        console.log('通过数字ID匹配到仓库:', matchedWarehouse);
      }
    }
  }
  
  // 3. 如果没匹配到，尝试作为仓库名称匹配
  if (!matchedWarehouse) {
    matchedWarehouse = state.warehouseList.find(w => w.name === warehouseKey);
    if (matchedWarehouse) {
      console.log('通过名称匹配到仓库:', matchedWarehouse);
    }
  }
  
  // 4. 如果还没匹配到，尝试作为仓库编码匹配
  if (!matchedWarehouse) {
    matchedWarehouse = state.warehouseList.find(w => w.code === warehouseKey);
    if (matchedWarehouse) {
      console.log('通过编码匹配到仓库:', matchedWarehouse);
    }
  }
  
  // 5. 如果还没匹配到，尝试模糊匹配名称
  if (!matchedWarehouse) {
    matchedWarehouse = state.warehouseList.find(w => 
      w.name?.includes(warehouseKey) || warehouseKey.includes(w.name)
    );
    if (matchedWarehouse) {
      console.log('通过模糊匹配到仓库:', matchedWarehouse);
    }
  }
  
  if (matchedWarehouse) {
    state.form.warehouseId = matchedWarehouse.id;
    console.log('已设置仓库ID:', matchedWarehouse.id);
    
    // 自动加载对应的库位列表
    await onWarehouseChange(matchedWarehouse.id);
  } else {
    console.log('未找到匹配的仓库，尝试的关键字:', warehouseKey);
  }
};

// 根据商品名称查询对应的仓库
const loadWarehouseByGoodsName = async (goodsName: string) => {
  if (!goodsName) {
    console.log('商品名称为空，无法查询仓库');
    return;
  }
  
  console.log('开始查询商品对应的仓库，商品名称:', goodsName);
  
  try {
    // 先尝试通过货品编码查询
    let res = await goodsApi.page({
      page: 1,
      pageSize: 10,
      goodsCode: goodsName
    });
    
    let goodsList = res.data?.result?.items || res.data?.result || [];
    console.log('通过货品编码查询结果:', goodsList);
    
    // 如果通过编码没找到，再尝试通过名称查询
    if (goodsList.length === 0) {
      res = await goodsApi.page({
        page: 1,
        pageSize: 10,
        goodsName: goodsName
      });
      
      goodsList = res.data?.result?.items || res.data?.result || [];
      console.log('通过货品名称查询结果:', goodsList);
    }
    
    if (goodsList.length > 0) {
      const goods = goodsList[0];
      const warehouseId = goods.goodsWareId;
      
      console.log('找到货品信息:', goods);
      console.log('货品对应的仓库ID:', warehouseId);
      
      if (warehouseId) {
        // 设置仓库ID
        state.form.warehouseId = warehouseId;
        console.log('已设置仓库ID:', warehouseId);
        
        // 自动加载对应的库位列表
        await onWarehouseChange(warehouseId);
      } else {
        console.log('货品没有关联仓库');
      }
    } else {
      console.log('未找到匹配的货品信息');
    }
  } catch (error) {
    console.error('查询货品仓库失败:', error);
    // 不显示错误消息，因为这只是辅助功能
  }
};

// 加载仓库列表
const loadWarehouseList = async () => {
  try {
    const res = await warehouseApi.page({
      page: 1,
      pageSize: 1000, // 获取所有仓库
      wareType: true // 只获取启用的仓库
    });
    
    // 转换数据格式
    state.warehouseList = (res.data?.result?.items || res.data?.result || []).map((warehouse: any) => ({
      id: warehouse.id,
      name: warehouse.wareName,
      code: warehouse.wareCode,
      address: warehouse.wareAddr
    }));
  } catch (error) {
    console.error('加载仓库列表失败:', error);
    ElMessage.error('加载仓库列表失败');
    // 如果API调用失败，使用空数组
    state.warehouseList = [];
  }
};

// 仓库变化时加载库位列表
const onWarehouseChange = async (warehouseId: any) => {
  state.form.locationId = null;
  state.locationList = [];
  
  if (!warehouseId) return;
  
  console.log('开始加载库位列表，仓库ID:', warehouseId);
  
  try {
    // 直接传入 warehouseId，让后端进行过滤
    const res = await warePlaceApi.page({
      page: 1,
      pageSize: 1000, // 获取所有库位
      warehouseId: Number(warehouseId), // 按仓库ID筛选库位
      warePlaceType: true // 只获取启用的库位
    });
    
    console.log('库位API返回数据:', res);
    console.log('原始库位列表:', res.data?.result?.items || res.data?.result);
    
    // 转换数据格式
    state.locationList = (res.data?.result?.items || res.data?.result || []).map((location: any) => ({
      id: location.id,
      name: location.warePlaceName,
      code: location.warePlaceCode,
      volume: location.warePlaceVolume,
      warehouseId: location.warehouseId
    }));
    
    console.log('转换后的库位列表:', state.locationList);
    
    if (state.locationList.length === 0) {
      console.warn('该仓库下没有可用的库位');
      ElMessage.warning('该仓库下没有可用的库位，请先添加库位');
    } else {
      console.log(`成功加载 ${state.locationList.length} 个库位`);
    }
  } catch (error) {
    console.error('加载库位列表失败:', error);
    ElMessage.error('加载库位列表失败');
    // 如果API调用失败，使用空数组
    state.locationList = [];
  }
};

// 确认盘点
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    state.loading = true;
    
    // 获取仓库名称和库位名称
    const selectedWarehouse = state.warehouseList.find(w => w.id === state.form.warehouseId);
    const warehouseName = selectedWarehouse?.name || '未知仓库';
    const selectedLocation = state.locationList.find(l => l.id === state.form.locationId);
    const locationName = selectedLocation?.name || '未知库位';
    
    // 获取盘点类型中文名称
    const stocktakingTypeMap: { [key: string]: string } = {
      'inventory': '存货盘点',
      'periodEnd': '期末盘点',
      'periodStart': '期初盘点'
    };
    const stocktakingTypeName = stocktakingTypeMap[state.form.stocktakingType] || '存货盘点';
    
    // 获取盘点结果中文名称
    const stocktakingResultMap: { [key: string]: string } = {
      'surplus': '盘盈',
      'loss': '盘亏',
      'match': '账实相符'
    };
    const stocktakingResultName = stocktakingResultMap[state.form.stocktakingResult] || '';
    
    let generatedOrderCode = '';
    
    // 根据盘点结果执行不同操作
    if (state.form.stocktakingResult === 'surplus') {
      // 盘盈：生成入库单
      const instockCode = `RKDH${Date.now()}`;
      generatedOrderCode = instockCode;
      
      await instockApi.add({
        code: instockCode,
        inType: '盘盈入库',
        documentStatus: 6, // 已完成状态
        inDate: new Date().toISOString().split('T')[0],
        warehouseName: warehouseName,
        warePlaceName: locationName,
        relatedCode: state.form.orderCode,
        goodsName: state.form.goodsName,
        agentName: '系统操作员',
        inQuantity: state.form.profitQuantity,
        warehouseAmount: state.form.profitAmount,
        remark: `盘点单：${state.form.orderCode} | 盘点结果：盘盈 | 盘盈数量：${state.form.profitQuantity} | 盘盈金额：${state.form.profitAmount} | ${state.form.remark || ''}`
      });
      
      console.log('已生成盘盈入库单:', instockCode);
      
    } else if (state.form.stocktakingResult === 'loss') {
      // 盘亏：生成出库单
      const outstockCode = `CKDH${Date.now()}`;
      generatedOrderCode = outstockCode;
      
      await outstockApi.add({
        code: outstockCode,
        outType: '盘亏出库',
        documentStatus: 6, // 已完成状态
        outDate: new Date().toISOString().split('T')[0],
        warehouseName: warehouseName,
        warePlaceName: locationName,
        relatedCode: state.form.orderCode,
        goodsName: state.form.goodsName,
        agentName: '系统操作员',
        outQuantity: state.form.lossQuantity,
        warehouseAmount: state.form.lossAmount,
        remark: `盘点单：${state.form.orderCode} | 盘点结果：盘亏 | 盘亏数量：${state.form.lossQuantity} | 盘亏金额：${state.form.lossAmount} | ${state.form.remark || ''}`
      });
      
      console.log('已生成盘亏出库单:', outstockCode);
      
    } else if (state.form.stocktakingResult === 'match') {
      // 账实相符：不生成入库单或出库单
      console.log('账实相符，无需生成出入库单');
    }
    
    // 更新盘点单表数据
    await stocktakingApi.update({
      id: state.form.orderId,
      code: state.form.orderCode,
      warehouseName: String(state.form.warehouseId), // 存储仓库ID
      goodsName: state.form.goodsName,
      quantity: state.form.stocktakingQuantity,
      stockTakingType: state.form.stocktakingType,
      inventoryResult: state.form.stocktakingResult,
      profitQuantity: state.form.profitQuantity,
      profitAmount: state.form.profitAmount,
      lossQuantity: state.form.lossQuantity,
      lossAmount: state.form.lossAmount,
      documentStatus: 6, // 已完成状态
      inStatus: 6, // 入库状态：已完成
      outStatus: 6, // 出库状态：已完成
      remark: state.form.remark,
      endTime: new Date().toISOString()
    });
    
    console.log('已更新盘点单数据');
    
    // 成功提示
    if (state.form.stocktakingResult === 'surplus') {
      ElMessage.success(`盘点操作成功！已生成盘盈入库单：${generatedOrderCode}`);
    } else if (state.form.stocktakingResult === 'loss') {
      ElMessage.success(`盘点操作成功！已生成盘亏出库单：${generatedOrderCode}`);
    } else {
      ElMessage.success('盘点操作成功！账实相符，已更新盘点单数据');
    }
    
    // 触发确认事件，通知父组件刷新数据
    emit('confirm', {
      ...state.form,
      generatedOrderCode: generatedOrderCode,
      warehouseName: warehouseName,
      locationName: locationName
    });
    
    handleClose();
  } catch (error: any) {
    console.error('盘点操作失败:', error);
    ElMessage.error('盘点操作失败：' + (error.message || '未知错误'));
  } finally {
    state.loading = false;
  }
};

// 关闭对话框
const handleClose = () => {
  state.dialogVisible = false;
  state.form = {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    currentStatus: '',
    warehouseId: null,
    locationId: null,
    stocktakingQuantity: 0,
    stocktakingType: 'inventory',
    stocktakingResult: '',
    profitQuantity: 0,
    profitAmount: 0,
    lossQuantity: 0,
    lossAmount: 0,
    remark: ''
  };
  emit('cancel');
};

defineExpose({
  openDialog
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>

